﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace LibraryManagement
{
    public partial class ReaderDashboard : Form
    {
        private Form parentForm;
        private int userId;

        public ReaderDashboard(Form parent, int userId)
        {
            InitializeComponent();
            parentForm = parent;
            this.userId = userId;
            LoadAvailableBooks();
        }

        private void LoadAvailableBooks()
        {
            string query = "SELECT * FROM Books WHERE Stock > 0 AND Status = '在库'";
            DataTable dt = DatabaseHelper.ExecuteQuery(query);
            dgvAvailableBooks.DataSource = dt;
        }

        //private void btnReserveBook_Click(object sender, EventArgs e)
        //{
        //    int bookId = (int)dgvAvailableBooks.SelectedRows[0].Cells["BookID"].Value;
        //    string expirationDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");

        //    string query = $"INSERT INTO BookReservations (BookID, UserID, ExpirationDate) VALUES ({bookId}, {userId}, '{expirationDate}')";
        //    DatabaseHelper.ExecuteNonQuery(query);

        //    string updateStockQuery = $"UPDATE Books SET Stock = Stock - 1 WHERE BookID = {bookId}";
        //    DatabaseHelper.ExecuteNonQuery(updateStockQuery);

        //    MessageBox.Show("预约成功！");
        //    LoadAvailableBooks();
        //}

        //private void btnBack_Click(object sender, EventArgs e)
        //{
        //    parentForm.Show();
        //    this.Close();
        //}

        private void btnReserveBook_Click_1(object sender, EventArgs e)
        {
            //int bookId = (int)dgvAvailableBooks.SelectedRows[0].Cells["BookID"].Value;
            //string expirationDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");

            //string query = $"INSERT INTO BookReservations (BookID, UserID, ExpirationDate) VALUES ({bookId}, {userId}, '{expirationDate}')";
            //DatabaseHelper.ExecuteNonQuery(query);

            //string updateStockQuery = $"UPDATE Books SET Stock = Stock - 1 WHERE BookID = {bookId}";
            //DatabaseHelper.ExecuteNonQuery(updateStockQuery);

            //MessageBox.Show("预约成功！");
            //LoadAvailableBooks();

            try
            {
                // 检查是否有选中行
                if (dgvAvailableBooks.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择一本书！");
                    return;
                }

                // 获取选中行
                DataGridViewRow selectedRow = dgvAvailableBooks.SelectedRows[0];

                // 检查 BookID 列
                if (selectedRow.Cells["BookID"].Value == null)
                {
                    MessageBox.Show("无法获取图书 ID，请检查数据！");
                    return;
                }

                int bookId = (int)selectedRow.Cells["BookID"].Value;

                // 检查库存
                int stock = (int)selectedRow.Cells["Stock"].Value;
                if (stock <= 0)
                {
                    MessageBox.Show("库存不足，无法预约！");
                    return;
                }

                // 插入预约记录
                string expirationDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");
                string query = $"INSERT INTO BookReservations (BookID, UserID, ExpirationDate) VALUES ({bookId}, {userId}, '{expirationDate}')";
                DatabaseHelper.ExecuteNonQuery(query);

                // 更新库存
                string updateStockQuery = $"UPDATE Books SET Stock = Stock - 1 WHERE BookID = {bookId}";
                DatabaseHelper.ExecuteNonQuery(updateStockQuery);

                //更新日志
                string logQuery = $"INSERT INTO Logs (Action, BookID, Operator, Date) VALUES ('ReserveBook', {bookId}, '{userId}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
                DatabaseHelper.ExecuteNonQuery(logQuery);

                MessageBox.Show("预约成功！");
                LoadAvailableBooks();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}\n{ex.StackTrace}");
            }
        }

        private void btnBack_Click_1(object sender, EventArgs e)
        {
            parentForm.Show();
            this.Close();
        }

        private void dgvAvailableBooks_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
